package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 调用与当前类Test5所在同一个包中被注解@AutoRunClass标注的类中那些被注解@AutoRunMethod标注的方法
 */
public class Test5 {
    public static void main(String[] args) throws Exception {
        File dir = new File(Test5.class.getResource(".").toURI());
        String packName = Test5.class.getPackage().getName();
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(packName + "." + className);
            boolean tf = cls.isAnnotationPresent(AutoRunClass.class);
            Object obj;
            if (tf) {
                System.out.println(className + "类被@AutoRunClass标注了");
                obj = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        System.out.println(method.getName()+"被标注了");
                        method.invoke(obj);
                    }
                }
            }
        }


        /*File dir = new File(Test5.class.getResource(".").toURI());
        String packName = Test5.class.getPackage().getName();
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(packName + "." + className);
            boolean tf = cls.isAnnotationPresent(AutoRunClass.class);
            if (tf == false) {
                continue;
            }
            System.out.println(className + "类被@AutoRunClass标注了");
            Object obj = cls.newInstance();
            Method[] methods = cls.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(AutoRunMethod.class)) {
                    method.invoke(obj);
                }
            }
        }*/
    }
}